#include "UdpServer.hpp"
#include <memory>
#include <iostream>
#include <vector>
#include "Comm.hpp"
using namespace std;

void Usage(std::string proc)
{
    std::cout << "Usage: \n\t" << proc << " local_ip local_port\n"
              << std::endl;
}

// 默认消息
std::string OnMessageDefalut(std::string request)
{
    return request + "[ haha,got you !]";
}

std::vector<std::string> black_words = {
    "rm",
    "unlink",
    "cp",
    "mv",
    "chmod",
    "exit",
    "reboot",
    "halt",
    "shutdown"};

bool SafeCheck(std::string command)
{
    for (auto &k : black_words)
    {
        auto pos = command.find(k);
        if (pos != std::string::npos)
            return 0;
    }
    return 1;
}

std::string ExecuteCommand(std::string command)
{

    if (!SafeCheck(command))
        return "bad man!!";

    std::cout << "get a message: " << command << std::endl;
    FILE *fp = popen(command.c_str(), "r");
    // 自动创建管道，自动fork创建子进程，然后子进程程序替换，执行命令
    // 执行结果在popen的返回值中，以文件的方式读取
    // 失败返回NULL
    if (fp == nullptr)
    {
        return "execute error, reason is unkown";
    }

    std::string response;
    char buffer[1024];

    while (true)
    {
        char *s = fgets(buffer, sizeof buffer, fp); // fgets ???
        if (!s)
            break;
        else
            response += buffer;
    }

    pclose(fp);
    return response.empty() ? "success" : response;
}

int main(int argc, char *argv[])
{
    if (argc != 2) // 参数数量
    {
        Usage(argv[0]);
        return Usage_Err;
    }

    // std::string ip = argv[1];
    uint16_t port = std::stoi(argv[1]);

    //std::unique_ptr<UdpServer> usvr = std::make_unique<UdpServer>(ExecuteCommand); // 目前用的是初始值

    std::unique_ptr<UdpServer> usvr = std::make_unique<UdpServer>(); // 目前用的是初始值

    usvr->Init();
    usvr->Start();
}